<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends Console_Controller{
	
	public function __construct(){
		parent::__construct();
		$this->load->model('admin_model');
	}
	
	public function index(){
		$gets = $this->input->get();
		$where = [];
		$assign = [
			'gets' => $gets,
			'options' => [
				'group' => $this->admin_model->group()
			]
		];
		$total = $this->admin_model->get_total($where);
		if($total > 0){
			$this->load->library('pagination', [
				'total_num' => $total
			]);
			$assign['show_page'] = $this->pagination->create();
			$assign['list'] = $this->admin_model->get_result([
				'where' => $where,
				'start' => $this->pagination->limit_start,
				'limit' => $this->pagination->page_size
			]);
		}
		$this->ci_smarty->assign($assign);
		$this->ci_smarty->display('admin_list.htm');
	}
	
	public function create(){
		$this->render('create');
	}
	
	public function edit(){
		$this->render('edit');
	}
	
	private function render($action){
		$assign = [
			'action' => $action,
			'gets' => $this->input->get(),
			'options' => [
				'group' => $this->admin_model->group()
			]
		];
		switch($action){
			case 'create':
				$assign['title'] = '新增管理员';
				break;
			case 'edit':
				$assign['title'] = '修改管理员';
				$info = $this->admin_model->get_row([
					'where' => [
						'id' => $this->input->get('id')
					]
				]);
				break;
			default:
				$this->show_message();
		}
		$assign['info'] = $info;
		$this->ci_smarty->assign($assign);
		$this->ci_smarty->display('admin_set.htm');
	}
	
	public function submit(){
		$posts = $this->input->post();
		$olduser = $posts['old_username'];
		$username = $posts['username'];
		$password = $posts['password'];
		
		// 验证用户名是否被使用
		if(!$olduser || $olduser != $username){
			$row = $this->admin_model->get_row([
				'where' => [
					'username' => $username
				]
			]);
			if($row){
				$this->output_json('用户名已存在');
			}
		}
		
		$data = array(
			'username' => $username,
			'groupid' => $posts['groupid']
		);
		$this->load->helper('common');
		switch($posts['action']){
			case 'create':
				$data['password'] = mmd5($password);
				$data['createtime'] = time();
				break;
			case 'edit':
				if($password){
					$data['password'] = mmd5($password);
				}
				break;
			default:
				$this->output_json();
		}
		$query = $this->admin_model->set($data, $posts['id']);
		if($query){
			$this->output_json('提交成功', 0);
		}
		$this->output_json('提交失败');
	}
	
	public function delete(){
		$this->action('delete');
	}
	
	private function action($method){
		$actids = $this->input->post('actids');
		if(! $actids){
			$this->output_json();
		}
		switch($method){
			case 'delete':
				$query = $this->admin_model->del([
					'where_in' => [
						'id' => $actids
					]
				]);
				break;
			default:
				$this->output_json();
		}
		if($query){
			$this->output_json('操作成功', 0);
		}
		$this->output_json('操作失败');
	}
	
}
